/*
 * Copyright (c) 2012 Acorn International.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http:www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

YAHOO.namespace("card");
YAHOO.namespace("card.container");

YAHOO.util.Event.onDOMReady(function () {
    YAHOO.card.init = function () {
        var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event;


        var returnList = function (p_oEvent) {
            window.location.href = "/ozing/cards";
        };

        var refresh = function (p_oEvent) {
            window.location.href = "/ozing/card?cardId="+$('#cardId').html();
        };

        var returnUserListBtn = new YAHOO.widget.Button("returnListBtn", { onclick:{ fn:returnList } });
        var refreshUserEditBtn = new YAHOO.widget.Button("refreshBtn", { onclick:{ fn:refresh } });

        var myPaginator = new YAHOO.widget.Paginator({
            containers: ['card_transaction_paging'],
            rowsPerPage: 10,
            previousPageLinkClass: "yui-pg-previous gc-inbox-prev",
            nextPageLinkClass: "yui-pg-next gc-inbox-next"//,
            //template           : "<strong>{CurrentPageReport}</strong> {PreviousPageLink} {NextPageLink}",
            //pageReportTemplate : "{startIndex}-{endIndex} of {totalRecords}"
        });

        var myTableConfig = {
            paginator:myPaginator,
            MSG_EMPTY:'没有记录',
            dynamicData:true,
            initialLoad:false,
            width:'100%'
        };

        var myColumnDefs = [
            {key:"id", label:"ID", sortable:true},
            {key:"cardId", label:'卡号',sortable:true},
            {key:"txType", label:'交易类型',sortable:true},
            {key:"txTime", label:'交易时间', sortable:true},
            {key:"costPoint", label:'消耗币值',sortable:true}
        ];

        var cardHisDataSource = new YAHOO.util.DataSource('/ozing/user/cards/his/json?');
        cardHisDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        cardHisDataSource.responseSchema = {
            resultsList: 'records',
            metaFields: {
                totalRecords: 'totalRecords',
                paginationRecordOffset: "startIndex",
                paginationRowsPerPage: "pageSize",
                sortKey: "sort",
                sortDir: "dir"
            }
        };
        var cardHisDataTable = new YAHOO.widget.DataTable("card_transaction_table", myColumnDefs, cardHisDataSource, myTableConfig);

        // Show loading message while page is being rendered
        cardHisDataTable.showTableMessage(cardHisDataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

        // Integrate with Browser History Manager
        var History = YAHOO.util.History;

        // Define a custom function to route sorting through the Browser History Manager
        var handleSorting = function (oColumn) {
            // Calculate next sort direction for given Column
            var sDir = this.getColumnSortDir(oColumn);

            // The next state will reflect the new sort values
            // while preserving existing pagination rows-per-page
            // As a best practice, a new sort will reset to page 0
            var newState = generateRequest(0, oColumn.key, sDir, this.get("paginator").getRowsPerPage());

            // Pass the state along to the Browser History Manager
            History.navigate("cardHisTable", newState);
        };
        cardHisDataTable.sortColumn = handleSorting;

        // Define a custom function to route pagination through the Browser History Manager
        var handlePagination = function (state) {
            // The next state will reflect the new pagination values
            // while preserving existing sort values
            // Note that the sort direction needs to be converted from DataTable format to server value
            var sortedBy = this.get("sortedBy"),
                newState = generateRequest(
                    state.recordOffset, sortedBy.key, sortedBy.dir, state.rowsPerPage
                );

            // Pass the state along to the Browser History Manager
            History.navigate("cardHisTable", newState);
        };

        // First we must unhook the built-in mechanism...
        myPaginator.unsubscribe("changeRequest", cardHisDataTable.onPaginatorChangeRequest);
        // ...then we hook up our custom function
        myPaginator.subscribe("changeRequest", handlePagination, cardHisDataTable, true);

        // Update totalRecords on the fly with values from server
        cardHisDataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
            var meta = oResponse.meta;
            oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
            oPayload.pagination = {
                rowsPerPage: meta.paginationRowsPerPage || 10,
                recordOffset: meta.paginationRecordOffset || 0
            };
            if(oPayload.totalRecords==undefined){
                oPayload.totalRecords=0;
            }
            oPayload.sortedBy = {
                key: meta.sortKey || "id",
                dir: (meta.sortDir) ? "yui-dt-" + meta.sortDir : "yui-dt-asc" // Convert from server value to DataTable format
            };
            return true;
        };

        var generateRequest = function (startIndex, sortKey, dir, results) {
            var cardId = encodeURIComponent($("#cardId").html());
            startIndex = startIndex || 0;
            sortKey = sortKey || "id";
            dir = (dir) ? dir.substring(7) : "desc";  //Converts from DataTable format "yui-dt-[dir]" to server value "[dir]"
            results = results || 10;
            return  "&sort=" + sortKey + "&dir=" + dir +
                "&start_index=" + startIndex + "&num_per_page=" + results + "&cardId=" + cardId + "&time=" + new Date().getTime();
        };

        // Called by Browser History Manager to trigger a new state
        var handleHistoryNavigation = function (request) {
            //show the "loading" message.
            cardHisDataTable.getTbodyEl().style.display = "none";
            cardHisDataTable.showTableMessage('正在加载中，请稍候...');

            // Sends a new request to the DataSource
            cardHisDataSource.sendRequest(request, {
                success: function () {
                    //checkUsersAll_btn.set("checked", false); //uncheck all.
                    cardHisDataTable.getTbodyEl().style.display = "";
                    cardHisDataTable.hideTableMessage();
                    cardHisDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                failure: function () {
                    //checkUsersAll_btn.set("checked", false); //uncheck all.
                    cardHisDataTable.getTbodyEl().style.display = "";
                    cardHisDataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                    cardHisDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                scope: cardHisDataTable,
                argument: {} // Pass in container for population at runtime via doBeforeLoadData
            });
        };

        // Calculate the first request
        var initialRequest = History.getBookmarkedState("cardHisTable") || // Passed in via URL
            generateRequest(); // Get default values

        // Register the module
        History.register("cardHisTable", initialRequest, handleHistoryNavigation);

        // Render the first view
        History.onReady(function () {
            // Current state after BHM is initialized is the source of truth for what state to render
            var currentState = History.getCurrentState("cardHisTable");
            handleHistoryNavigation(currentState);
        });

        var renderPage = function () {
            var currentState = History.getCurrentState("cardHisTable") || generateRequest();
            handleHistoryNavigation(currentState);
        };

        History.onReady(function () {
            renderPage();
        });

        // Initialize the Browser History Manager.
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

        return {
            oDS_cards: myDataSource_card,
            oDT_cards: myDataTable_cards,
            oDS_his: cardHisDataSource,
            oDT_his: cardHisDataTable
        };
    }();
});